package com.cbs.android.function.imagecrop;

import android.content.Intent;
import android.net.Uri;

import com.cbs.android.component.application.activity.CBSActivity;
import com.cbs.android.component.application.activity.handler.CBSActivityResultHandler;

import java.lang.ref.WeakReference;

/**
 * Builder for crop Intents and utils for handling result
 */
public class ImageCropFunction {
    private static final int REQUEST_IMAGECROP = 0xFFDF;

    interface Extra {
        String ASPECT_X = "aspect_x";
        String ASPECT_Y = "aspect_y";
        String MAX_X = "max_x";
        String MAX_Y = "max_y";
    }

    /**
     * Send the crop Intent from an Activity with a custom request code
     * default:
     * aspect_x = 1
     * aspect_y = 1
     * max_x = 256
     * max_y = 256
     *
     * @param activity Activity to receive result
     */
    public static void start(CBSActivity activity, Uri sourceUri, ImageCropHandler handler) {
        start(activity, sourceUri, 1, 1, 256, 256, handler);
    }

    public static void start(CBSActivity activity, Uri sourceUri, int aspect_x, int aspect_y, int max_x, int max_y, ImageCropHandler handler) {
        activity.addActivityResultHandler(new MyActivityResultHandler(activity, handler));
        Intent intent = new Intent(activity, CropImageActivity.class);
        intent.setData(sourceUri);
        intent.putExtra(Extra.ASPECT_X, aspect_x);
        intent.putExtra(Extra.ASPECT_Y, aspect_y);
        intent.putExtra(Extra.MAX_X, max_x);
        intent.putExtra(Extra.MAX_Y, max_y);
        activity.startActivityForResult(intent, REQUEST_IMAGECROP);
    }

    private static class MyActivityResultHandler implements CBSActivityResultHandler {
        private CBSActivityResultHandler handler;
        private WeakReference<CBSActivity> activityWeakReference;

        public MyActivityResultHandler(CBSActivity activity, CBSActivityResultHandler handler) {
            this.handler = handler;
            activityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void onActivityResult(int requestCode, int responseCode, Intent intent) {
            if (requestCode == REQUEST_IMAGECROP) {
                if (handler != null) {
                    handler.onActivityResult(requestCode, responseCode, intent);
                }
                if (activityWeakReference != null && activityWeakReference.get() != null) {
                    activityWeakReference.get().removeActivityResultHandler(this);
                }
            }
        }
    }
}
